package com.wasion.gydpe.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.jxls.exception.ParsePropertyException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.wasion.gydpe.common.util.ConfigUtil;
import com.wasion.gydpe.common.util.JxlsUtil;
import com.wasion.gydpe.exception.DataAccessException;
import com.wasion.gydpe.model.Bureau;
import com.wasion.gydpe.model.Line;
import com.wasion.gydpe.model.Node;
import com.wasion.gydpe.model.Station;
import com.wasion.gydpe.service.ArchivesService;

/**
 * 
 * @ClassName: ArchivesAction
 * @Description: 档案管理控制层Action
 * @author 高意
 * @date Sep 25, 2012 10:03:26 AM
 * 
 */
@ParentPackage("gydpe-default")
@Namespace("/archives")
@Results( {
		@Result(name = "bureauListSuccess", location = "/jsp/archivesMgmt/bureauMgmt.jsp"),
		@Result(name = "stationListSuccess", location = "/jsp/archivesMgmt/stationMgmt.jsp"),
		@Result(name = "lineListSuccess", location = "/jsp/archivesMgmt/lineMgmt.jsp"),
		@Result(name = "terminalListSuccess", location = "/jsp/archivesMgmt/terminalMgmt.jsp"),
		@Result(name = "indicatorListSuccess", location = "/jsp/archivesMgmt/indicatorMgmt.jsp"),
		@Result(name = "error", location = "/jsp/common/error/error.jsp") })
@ExceptionMappings( { @ExceptionMapping(exception = "java.lang.Exception", result = "error") })
@Controller
public class ArchivesAction extends BaseAction {

	private static final long serialVersionUID = -4389853185958383263L;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ArchivesAction.class);

	private static final String EXCEPTION_MSG = "发生错误了，请联系管理员...";

	@Resource
	private ArchivesService archivesService;

	private String flag; // 标识
	private String bureauNo; // 供电局编号
	private String bureauName; // 供电局名称
	private String bureauAddr; // 供电局地址
	private String bureauTelephone; // 电话
	private String bureauId; // 供电局Id
	private String stationId; // 供电所Id
	private String stationNo; // 供电所编号
	private String stationName; // 供电所名称
	private String stationAddr; // 供电所地址
	private String stationTelephone; // 供电所电话
	private List<Bureau> bureauList; // 供电局集
	private String lineName; // 线路名称
	private String lineId; // 线路id
	private String lineNo; // 线路编号
	private String svgId; // svg Id
	private String svgFilePath; // svg文件路径
	private String terminalAddr; // 终端地址
	private String terminalId; // 终端id
	private String msg = ""; // 消息
	private String id; // 树唯一标识
	private JSONObject jsonObject; // datagrid封装的json格式数据

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getBureauNo() {
		return bureauNo;
	}

	public void setBureauNo(String bureauNo) {
		this.bureauNo = bureauNo;
	}

	public String getBureauName() {
		return bureauName;
	}

	public void setBureauName(String bureauName) {
		this.bureauName = bureauName;
	}

	public String getBureauAddr() {
		return bureauAddr;
	}

	public void setBureauAddr(String bureauAddr) {
		this.bureauAddr = bureauAddr;
	}

	public String getBureauTelephone() {
		return bureauTelephone;
	}

	public void setBureauTelephone(String bureauTelephone) {
		this.bureauTelephone = bureauTelephone;
	}

	public String getBureauId() {
		return bureauId;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setBureauId(String bureauId) {
		this.bureauId = bureauId;
	}

	public String getStationId() {
		return stationId;
	}

	public void setStationId(String stationId) {
		this.stationId = stationId;
	}

	public String getStationNo() {
		return stationNo;
	}

	public void setStationNo(String stationNo) {
		this.stationNo = stationNo;
	}

	public String getStationName() {
		return stationName;
	}

	public void setStationName(String stationName) {
		this.stationName = stationName;
	}

	public String getStationAddr() {
		return stationAddr;
	}

	public void setStationAddr(String stationAddr) {
		this.stationAddr = stationAddr;
	}

	public String getStationTelephone() {
		return stationTelephone;
	}

	public void setStationTelephone(String stationTelephone) {
		this.stationTelephone = stationTelephone;
	}

	public String getLineId() {
		return lineId;
	}

	public void setLineId(String lineId) {
		this.lineId = lineId;
	}

	public String getLineName() {
		return lineName;
	}

	public void setLineName(String lineName) {
		this.lineName = lineName;
	}

	public String getLineNo() {
		return lineNo;
	}

	public void setLineNo(String lineNo) {
		this.lineNo = lineNo;
	}

	public List<Bureau> getBureauList() {
		return bureauList;
	}

	public void setBureauList(List<Bureau> bureauList) {
		this.bureauList = bureauList;
	}

	public String getSvgId() {
		return svgId;
	}

	public void setSvgId(String svgId) {
		this.svgId = svgId;
	}

	public String getSvgFilePath() {
		return svgFilePath;
	}

	public void setSvgFilePath(String svgFilePath) {
		this.svgFilePath = svgFilePath;
	}

	public String getTerminalAddr() {
		return terminalAddr;
	}

	public void setTerminalAddr(String terminalAddr) {
		this.terminalAddr = terminalAddr;
	}

	public String getTerminalId() {
		return terminalId;
	}

	public void setTerminalId(String terminalId) {
		this.terminalId = terminalId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	/**
	 * 
	 * @Title: list
	 * @Description: 档案管理，根据flag标记的不同进行跳转
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "list")
	public String list() {

		if (null != flag) {
			if ("bureau".equals(flag)) {
				return "bureauListSuccess";
			} else if ("station".equals(flag)) {
				return "stationListSuccess";
			} else if ("line".equals(flag)) {
				return "lineListSuccess";
			} else if ("terminal".equals(flag)) {
				return "terminalListSuccess";
			} else if ("indicator".equals(flag)) {
				return "indicatorListSuccess";
			}
		}

		return "error";
	}

	/**
	 * 
	 * @Title: showBureaus
	 * @Description: 分页显示供电局列表
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showBureaus")
	public void showBureaus() throws Exception {

		// 当前页
		int currPage = Integer.parseInt((page == null || page == "0") ? "1"
				: page);
		// 每页显示条数
		int rowsPerPage = Integer.parseInt((rows == null || rows == "0") ? "10"
				: rows);

		int fromNo = (currPage - 1) * rowsPerPage;

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("bureauName", get(bureauName));
		paramsMap.put("bureauAddr", get(bureauAddr));
		paramsMap.put("bureauTelephone", get(bureauTelephone));
		paramsMap.put("fromNo", fromNo);
		paramsMap.put("rowsPerPage", rowsPerPage);

		try {
			jsonObject = archivesService.queryBureausByPaging(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("分页查询供电局失败：showBureaus >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: exportBureaus
	 * @Description: 导出供电局信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action("exportBureaus")
	public void exportBureaus() {

		List<Bureau> list = null;
		try {
			list = archivesService.queryAllBureaus();
		} catch (DataAccessException e) {
			LOGGER.error("查询全部供电局失败：exportBureaus >>>>>> " + e);
			e.printStackTrace();
		}

		// 准备参数，调用导出excel的工具方法
		Map<String, Object> datumMap = new HashMap<String, Object>();
		datumMap.put("bureauInfo", list);
		datumMap.put("date", new Timestamp(System.currentTimeMillis())
				.toString().split(" ")[0]);
		String templateFilePath = ServletActionContext.getServletContext()
				.getRealPath(ConfigUtil.getValueByKey("templatePath"))
				+ "/" + ConfigUtil.getValueByKey("bueauTemplateFileName");
		String destFileName = ConfigUtil.getValueByKey("exportBureausFileName");
		HttpServletResponse response = ServletActionContext.getResponse();

		try {
			JxlsUtil.exportExcel(destFileName, templateFilePath, datumMap,
					response);
		} catch (ParsePropertyException e) {
			e.printStackTrace();
			LOGGER.error("导出excel失败：exportBureaus >>>>>> " + e);
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error("导出excel失败：exportBureaus >>>>>> " + e);
		}
	}

	/**
	 * 
	 * @Title: removeBureauById
	 * @Description: 根据id删除供电局
	 * @param
	 * @return
	 * @throws
	 */
	public String removeBureauById() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("bureauId", get(bureauId));

		try {
			boolean isSucc = archivesService.removeBureau(paramsMap);
			msg = isSucc ? "删除成功！" : "删除失败！";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除供电局失败：removeBureauById >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		return SUCCESS;
	}

	/**
	 * 
	 * @Title: loadBureauByPk
	 * @Description: 根据主键装载供电局信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "loadBureauByPk")
	public void loadBureauByPk() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("bureauId", get(bureauId));

		try {
			jsonObject = archivesService.loadBureauByPk(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("根据主键装载供电局信息：loadBureauByPk >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: addOrModifyBureau
	 * @Description: 新增或者修改供电局
	 * @param
	 * @return
	 * @throws
	 */
	public String addOrModifyBureau() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("bureauId", get(bureauId));
		paramsMap.put("bureauNo", get(bureauNo));
		paramsMap.put("bureauName", get(bureauName));
		paramsMap.put("bureauAddr", get(bureauAddr));
		paramsMap.put("bureauTelephone", get(bureauTelephone));

		try {
			msg = archivesService.addOrModifyBureau(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("新增或修改供电局失败：addOrModifyBureau >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @Title: showStations
	 * @Description: 分页显示供电所列表
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showStations")
	public void showStations() throws Exception {

		// 当前页
		int currPage = Integer.parseInt((page == null || page == "0") ? "1"
				: page);
		// 每页显示条数
		int rowsPerPage = Integer.parseInt((rows == null || rows == "0") ? "10"
				: rows);

		int fromNo = (currPage - 1) * rowsPerPage;

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("stationName", get(stationName));
		paramsMap.put("stationAddr", get(stationAddr));
		paramsMap.put("stationTelephone", get(stationTelephone));

		paramsMap.put("fromNo", fromNo);
		paramsMap.put("rowsPerPage", rowsPerPage);

		try {
			jsonObject = archivesService.queryStationsByPaging(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("分页查询供电所失败：showStations >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: showAllBureaus
	 * @Description: 显示所有的供电局信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showAllBureaus")
	public void showAllBureaus() {

		try {
			bureauList = archivesService.queryAllBureaus();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("查询所有的供电所失败：showAllBureaus >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		JSONArray jArray = JSONArray.fromObject(bureauList);
		this.printToViewJustResult(jArray.toString());
	}

	/**
	 * 
	 * @Title: showStationsBelonged
	 * @Description: 级联显示局所属的供电所
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showStationsBelonged")
	public void showStationsBelonged() {

		List<Station> list = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("bureauId", get(bureauId));

		try {
			list = archivesService.queryStationsBelonged(params);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("查询局所属供电所失败：showStationsBelonged >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		JSONArray jArray = JSONArray.fromObject(list);
		this.printToViewJustResult(jArray.toString());
	}

	/**
	 * 
	 * @Title: loadStationByPk
	 * @Description: 根据主键装载供电所信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "loadStationByPk")
	public void loadStationByPk() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("stationId", get(stationId));

		try {
			jsonObject = archivesService.loadStationByPk(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("根据主键装载供电所信息：loadStationByPk >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: removeStationById
	 * @Description: 根据id删除供电所
	 * @param
	 * @return
	 * @throws
	 */
	public String removeStationById() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("stationId", get(stationId));

		try {
			boolean isSucc = archivesService.removeStation(paramsMap);
			msg = isSucc ? "删除成功！" : "删除失败！";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除供电所失败：removeStationById >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		return SUCCESS;
	}

	/**
	 * 
	 * @Title: addOrModifyStation
	 * @Description: 新增或者修改供电所
	 * @param
	 * @return
	 * @throws
	 */
	public String addOrModifyStation() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("stationId", get(stationId));
		paramsMap.put("stationNo", get(stationNo));
		paramsMap.put("bureauId", get(bureauId));
		paramsMap.put("stationName", get(stationName));
		paramsMap.put("stationAddr", get(stationAddr));
		paramsMap.put("stationTelephone", get(stationTelephone));

		try {
			msg = archivesService.addOrModifyStation(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("新增或修改供电所失败：addOrModifyStation >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @Title: showLines
	 * @Description: 分页显示线路列表
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showLines")
	public void showLines() throws Exception {

		// 当前页
		int currPage = Integer.parseInt((page == null || page == "0") ? "1"
				: page);
		// 每页显示条数
		int rowsPerPage = Integer.parseInt((rows == null || rows == "0") ? "10"
				: rows);

		int fromNo = (currPage - 1) * rowsPerPage;

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("lineName", get(lineName));
		paramsMap.put("fromNo", fromNo);
		paramsMap.put("rowsPerPage", rowsPerPage);

		try {
			jsonObject = archivesService.queryLinesByPaging(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("分页查询线路失败：showLines >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: removeLineById
	 * @Description: 根据id删除线路
	 * @param
	 * @return
	 * @throws
	 */
	public String removeLineById() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("lineId", get(lineId));

		try {
			boolean isSucc = archivesService.removeLine(paramsMap);
			msg = isSucc ? "删除成功！" : "删除失败！";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除线路失败：removeLineById >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		return SUCCESS;
	}

	/**
	 * 
	 * @Title: loadLineByPk
	 * @Description: 根据主键装载供电所信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "loadLineByPk")
	public void loadLineByPk() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("lineId", get(lineId));

		try {
			jsonObject = archivesService.loadLineByPk(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("根据主键装载线路信息：loadLineByPk >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: addOrModifyLine
	 * @Description: 新增或者修改线路
	 * @param
	 * @return
	 * @throws
	 */
	public String addOrModifyLine() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("lineId", get(lineId));
		paramsMap.put("stationId", get(stationId));
		paramsMap.put("lineNo", get(lineNo));
		paramsMap.put("lineName", get(lineName));
		paramsMap.put("svgId", get(svgId));
		paramsMap.put("svgFilePath", get(svgFilePath));

		try {
			msg = archivesService.addOrModifyLine(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("新增或修改线路失败：addOrModifyLine >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @Title: showTerminals
	 * @Description: 分页显示终端列表
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showTerminals")
	public void showTerminals() throws Exception {

		// 当前页
		int currPage = Integer.parseInt((page == null || page == "0") ? "1"
				: page);
		// 每页显示条数
		int rowsPerPage = Integer.parseInt((rows == null || rows == "0") ? "10"
				: rows);

		int fromNo = (currPage - 1) * rowsPerPage;

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("terminalAddr", get(terminalAddr));
		paramsMap.put("lineId", get(lineId));
		paramsMap.put("stationId", get(stationId));
		paramsMap.put("bureauId", get(bureauId));
		paramsMap.put("fromNo", fromNo);
		paramsMap.put("rowsPerPage", rowsPerPage);

		try {
			jsonObject = archivesService.queryTerminalsByPaging(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("分页查询终端失败：showTerminals >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: loadTerminalByPk
	 * @Description: 根据主键装载终端信息
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "loadTerminalByPk")
	public void loadTerminalByPk() {

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("terminalId", get(terminalId));
		paramsMap.put("lineId", get(lineId));

		try {
			jsonObject = archivesService.loadTerminalByPk(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("根据主键装载终端信息：loadTerminalByPk >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}
		this.printToViewJustResult(jsonObject.toString());
	}

	/**
	 * 
	 * @Title: showLinesBelonged
	 * @Description: 级联显示所所属的线路
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showLinesBelonged")
	public void showLinesBelonged() {

		List<Line> list = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("stationId", get(stationId));

		try {
			list = archivesService.queryLinesBelonged(params);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("查询所所属下的线路失败：showLinesBelonged >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		JSONArray jArray = JSONArray.fromObject(list);
		this.printToViewJustResult(jArray.toString());
	}

	/**
	 * 
	 * @Title: showAsyncLineTree
	 * @Description: 异步生成线路树
	 * @param
	 * @return
	 * @throws
	 */
	@Action(value = "showAsyncLineTree")
	public void showAsyncLineTree() {

		List<Node> list = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", get(id));
		params.put("level", 3);

		try {
			list = archivesService.queryAsyncTree(params);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("异步生成线路树：showAsyncLineTree >>>>>> " + e);
			msg = EXCEPTION_MSG;
		}

		JSONArray jArray = JSONArray.fromObject(list);
		this.printToViewJustResult(jArray.toString());
	}

	public List<Bureau> getAllBureaus() {

		List<Bureau> bureaus = new ArrayList<Bureau>();

		try {
			bureaus = archivesService.queryAllBureaus();
		} catch (DataAccessException e) {
			e.printStackTrace();
			LOGGER.error("报表失败...");
		}

		return bureaus;
	}

}
